<?php
namespace app\manage\model;

use think\Model;
use think\Db;

class UserWithdrawalsModel extends Model{
	//表名
	protected $table = 'ly_user_withdrawals';

	/**
	 * 提现记录
	 */
	public function withdrawalsList(){
		$param = input('get.');
		//查询条件组装
		$where = array();
		//分页参数组装
		$pageParam = array();
		// 状态搜索
		if (isset($param['isUser']) && $param['isUser'] == 1) $pageParam['isUser'] = $param['isUser'];
		//搜索类型
		if(isset($param['search_t']) && $param['search_t'] && isset($param['search_c']) && $param['search_c']){
			switch ($param['search_t']) {
				case 'username':
					$userId = model('Users')->where('username',$param['search_c'])->value('id');
					$where[] = array('ly_user_withdrawals.uid','=',$userId);
					break;
				case 'order_number':
					$where[] = array('order_number','=',$param['search_c']);
					break;
				case 'card_name':
					$where[] = array('card_name','=',$param['search_c']);
					break;
				case 'card_number':
					$where[] = array('card_number','=',$param['search_c']);
					break;
			}
			$pageParam['search_t'] = $param['search_t'];
			$pageParam['search_c'] = $param['search_c'];
		}
		
		//状态搜索
		if(isset($param['state']) && $param['state']){
			$where[] = array('ly_user_withdrawals.state','=',$param['state']);
			$pageParam['state'] = $param['state'];
		}
		// 时间
		if(isset($param['datetime_range']) && $param['datetime_range']){
			$dateTime = explode(' - ', $param['datetime_range']);
			$where[] = array('ly_user_withdrawals.time','>=',strtotime($dateTime[0]));
			$where[] = array('ly_user_withdrawals.time','<=',strtotime($dateTime[1]));
			$pageParam['datetime_range'] = $param['datetime_range'];
		}else{
			$todayStart = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$where[] = array('ly_user_withdrawals.time','>=',$todayStart);
			$todayEnd = mktime(23,59,59,date('m'),date('d'),date('Y'));
			$where[] = array('ly_user_withdrawals.time','<=',$todayEnd);
		}

		//查询符合条件的数据
		$resultData = $this->field('ly_user_withdrawals.*,manage.username as aname,users.username,danger,bank.bank_name')->join('users','ly_user_withdrawals.uid = users.id')->join('manage','ly_user_withdrawals.aid = manage.id','left')->join('bank','ly_user_withdrawals.bank_id = bank.id','left')->where($where)->order('time','desc')->paginate(16,false,['query'=>$pageParam]);
		//数据集转数组
		$withdrawalsList = $resultData->toArray()['data'];
		//部分元素重新赋值
		$stateColor = config('manage.color');
		$pageTotal['countPrice'] = 0;
		$pageTotal['countFee'] = 0;
		foreach ($withdrawalsList as $key => &$value) {
			$value['stateColor'] = $stateColor[$value['state']];
			//分页统计
			$pageTotal['countPrice'] += $value['price'];
			$pageTotal['countFee'] += $value['fee'];
		}

		// 权限查询
		$powerWhere = 'uid = '.session('manage_userid').' AND (cid = 3 OR role_id = 245)';
		$power = model('ManageUserRole')->getUserPower($powerWhere);

		return array(
			'data'				=>	$withdrawalsList,
			'pageTotal'			=>	$pageTotal,
			'page'				=>	$resultData->render(),//分页
			'where'				=>	$pageParam,
			'withdrawalsState'	=>	config('custom.withdrawalsState'),
			'power'				=>	$power,
		);
	}

	/**
	 * 风控审核view
	 */
	public function controlAuditView(){
		$param = input('get.');

		$data = $this->where('id',$param['id'])->find();

		return array(
			'data'	=>	$data
		);
	}

	/**
	 * 风控审核
	 */
	public function controlAudit(){
		$param = input('post.');
		if(!$param) return '提交失败';

		$controlAuditTime = cache('CA_controlAuditTime'.session('manage_userid')) ? cache('CA_controlAuditTime'.session('manage_userid')) : time()-2;
		if(time() - $controlAuditTime < 2){
			return ' 2 秒内不能重复提交';
		}
		cache('CA_controlAuditTime'.session('manage_userid'), time(), 10);

		$orderNumber = $param['order_number'];
		unset($param['order_number']);

		//获取订单信息
		$where[] = array('order_number','=',$orderNumber);
		$where[] = array('state','=',3);
		$orderInfo = $this->where($where)->find();
		if (!$orderInfo) return '订单不存在';
		$orderInfo = $orderInfo->toArray();
		// 更新订单
		$res = $this->where('order_number',$orderNumber)->update($param);
		if(!$res) return '操作失败1';

		switch ($param['examine']) {
			case 2:				
				//构造备注信息
				$remarksTemp = '订单 '.$orderInfo['order_number'].' 取款失败，退回资金：'.$orderInfo['price'];
				$remarks = (isset($param['remarks']) && $param['remarks'] && $param['remarks'] !== $orderInfo['remarks']) ? $param['remarks'] : $remarksTemp;
				//更新订单
				$orderUpdateArray = array(
					'aid'		=>	session('manage_userid'),
					'state'		=>	2,
					'set_time'	=>	time(),
					'remarks'	=>	$remarks
				);
				$res2 = $this->where('id',$orderInfo['id'])->update($orderUpdateArray);
				if(!$res2) {
					$this->where('id',$orderInfo['id'])->update($orderInfo);
					return '操作失败2';
				}

				//获取用户余额
				$balance = model('UserTotal')->field('balance')->where('uid',$orderInfo['uid'])->find();
				//更新用户余额
				$res3 = model('UserTotal')->where('uid',$orderInfo['uid'])->inc('balance',$orderInfo['price'])->update();
				if(!$res3) {
					$this->where('id',$orderInfo['id'])->update($orderInfo);
					return '操作失败3';
				}

				$res4 = model('TradeDetails')->where('order_number',$orderInfo['order_number'])->update(array('state'=>2,'remarks'=>'审核未通过，资金已退回'));
				if(!$res4) {
					$this->where('order_number',$orderNumber)->update($orderInfo);
					model('UserTotal')->where('uid',$orderInfo['uid'])->dec('balance',$orderInfo['price'])->update();
					return '操作失败4';
				}
				$tradeDetailsArray = array(
					'uid'                    =>	$orderInfo['uid'],
					'order_number'           =>	$orderInfo['order_number'],
					'trade_type'             =>	13,
					'trade_before_balance'   =>	$balance['balance'],
					'trade_amount'           =>	$orderInfo['price'],
					'account_balance'        =>	$balance['balance'] + $orderInfo['price'],
					//'account_frozen_balance' => $balance['frozen_balance'] - $orderInfo['price'],
					'remarks'                =>	$remarks,
					//'types'                  =>	2,
					'isadmin'                =>	1,
					//'isdaily'                => 2
				);
				$res4 = model('common/TradeDetails')->tradeDetails($tradeDetailsArray);
				if(!$res4) {
					$this->where('id',$orderInfo['id'])->update($orderInfo);
					model('UserTotal')->where('uid',$orderInfo['uid'])->dec('balance',$orderInfo['price'])->update();
					return '操作失败4';
				}

				//添加操作日志
				model('Actionlog')->actionLog(session('manage_username'),'审核订单号为'.$orderInfo['order_number'].'的提现订单。处理状态：审核未通过',1);
				break;
			
			case 1:
				//添加操作日志
				model('Actionlog')->actionLog(session('manage_username'),'审核订单号为'.$orderNumber.'的提现订单。处理状态：审核通过',1);
				break;
		}

		return 1;
	}

	/**
	 * 财务处理
	 */
	public function financialAudit(){
		$param = input('post.');
		if(!$param) return '提交失败';

		$controlAuditTime = cache('CA_financialAuditTime'.session('manage_userid')) ? cache('CA_financialAuditTime'.session('manage_userid')) : time()-2;
		if(time() - $controlAuditTime < 2){
			return ' 2 秒内不能重复提交';
		}
		cache('CA_financialAuditTime'.session('manage_userid'), time(), 10);
		
		$orderNumber = $param['order_number'];
		unset($param['order_number']);

		//获取订单信息
		$where[] = array('order_number','=',$orderNumber);
		//$where[] = array('state','=',3);
		$where[] = array('state','>=',3);
		$where[] = array('state','<=',5);
		$orderInfo = $this->where($where)->find();
		if (!$orderInfo) return '订单不存在';
		$orderInfo = $orderInfo->toArray();

		switch ($param['state']) {
			case 1://已支付
				//构造备注信息
				$remarks = (isset($param['remarks']) && $param['remarks'] && $param['remarks'] !== $orderInfo['remarks']) ? $param['remarks'] : '尊敬的用户您好！您的编号为'.$orderInfo['order_number'].' 的提现处理成功，金额￥'.$orderInfo['price'].'元 服务费：￥0.0000元，处理时间：'.date('Y-m-d H:i:s');
				//更新订单
				$orderUpdateArray = array(
					'aid'		=>	session('manage_userid'),
					'state'		=>	$param['state'],
					'set_time'	=>	time(),
					'remarks'	=>	$remarks
				);
				$res = $this->where('id',$orderInfo['id'])->update($orderUpdateArray);
				if(!$res) return '操作失败1';
				//更新流水
				$res2 = model('TradeDetails')->where('order_number',$orderNumber)->update(array('state'=>1));
				if(!$res2) return '操作失败3';
				// 获取余额
				$balance = model('UserTotal')->field('balance')->where('uid',$orderInfo['uid'])->find();
				// 扣除金额
				/*$res2 = model('UserTotal')->where('uid', $orderInfo['uid'])->setDec('frozen_balance', $orderInfo['price']);
				if (!$res2) {
					$this->where('id',$orderInfo['id'])->update($orderInfo);
					return '操作失败2';
				}*/
				// 流水
				$tradeDetailsArray = array(
					'uid'                    =>	$orderInfo['uid'],
					'trade_type'             =>	2,
					'trade_before_balance'   =>	$balance['balance'],
					'trade_amount'           =>	$orderInfo['price'],
					'account_balance'        =>	$balance['balance'],
					//'account_frozen_balance' => $balance['frozen_balance'] - $orderInfo['price'],
					'remarks'                =>	$remarks,
					//'types'                  =>	2,
					'isadmin'                =>	1,
				);
				$res3 = model('common/TradeDetails')->tradeDetails($tradeDetailsArray);
				if(!$res3) {
					$this->where('id',$orderInfo['id'])->update($orderInfo);
					//model('UserTotal')->where('uid', $orderInfo['uid'])->setInc('frozen_balance', $orderInfo['price']);
					return '操作失败3';
				}

				//添加操作日志
				model('Actionlog')->actionLog(session('manage_username'),'处理订单号为'.$orderInfo['order_number'].'的提现订单。处理状态：已支付',1);

				return 1;

				break;
			
			case 2://拒绝支付

				//构造备注信息
				$remarks = (isset($param['remarks']) && $param['remarks'] && $param['remarks'] !== $orderInfo['remarks']) ? $param['remarks'] : '订单 '.$orderInfo['order_number'].' 取款失败，退回资金：'.$orderInfo['price'];

				//更新订单
				$orderUpdateArray = array(
					'aid'		=>	session('manage_userid'),
					'state'		=>	$param['state'],
					'set_time'	=>	time(),
					'remarks'	=>	$remarks
				);
				$res = $this->where('order_number',$orderNumber)->update($orderUpdateArray);
				if(!$res) return '操作失败1';
				//更新流水
				$res1 = model('TradeDetails')->where('order_number',$orderInfo['order_number'])->update(array('state'=>2,'remarks'=>'提现失败，资金已退回'));
				if(!$res1) return '操作失败2';
				//获取用户余额
				$balance = model('UserTotal')->field('balance')->where('uid',$orderInfo['uid'])->find();
				//更新用户余额
				$res2 = model('UserTotal')->where('uid',$orderInfo['uid'])->inc('balance',$orderInfo['price'])->update();
				if(!$res2) {
					$this->where('id',$orderInfo['id'])->update($orderInfo);
					return '操作失败2';
				}

				$tradeDetailsArray = array(
					'uid'                    =>	$orderInfo['uid'],
					'order_number'           =>	$orderInfo['order_number'],
					'trade_type'             =>	13,
					'trade_before_balance'   =>	$balance['balance'],
					'trade_amount'           =>	$orderInfo['price'],
					'account_balance'        =>	$balance['balance'] + $orderInfo['price'],
					//'account_frozen_balance' => $balance['frozen_balance'] - $orderInfo['price'],
					'remarks'                =>	$remarks,
					//'types'                  =>	2,
					'isadmin'                =>	1,
					//'isdaily'                => 2
				);
				$res3 = model('common/TradeDetails')->tradeDetails($tradeDetailsArray);
				if(!$res3) {
					$this->where('id',$orderInfo['id'])->update($orderInfo);
					$res2 = model('UserTotal')->where('uid',$orderInfo['uid'])->dec('balance',$orderInfo['price'])->update();
					return '操作失败3';
				}

				//添加操作日志
				model('Actionlog')->actionLog(session('manage_username'),'处理订单号为'.$orderInfo['order_number'].'的提现订单。处理状态：拒绝支付',1);

				return 1;
				break;
			default:
				return '无须修改';
				break;
		}
	}

	/**
	 * 出款
	 */
	public function withdrawalsPayment(){
		if(!request()->isAjax()) return '非法提交';
		$param = input('param.');
		if(!$param) return '提交失败';
        $order = db('user_withdrawals')->where('id',$param['id'])->find();
        $uid = $order['uid'];
        $phone = Db::name('users')->where('id',$uid)->value('phone');
        $mail = model('users')->where('id',$uid)->value('mail');
        $ubank = Db::name('user_bank')->where('id',$order['bank_id'])->find();
        $orderNo = $order['order_number'];
        $data['type'] = 3;
        $data['mch_id'] = config('app.leappay.mchId');
        $data['order_sn'] = $orderNo;
        $data['money'] = sprintf("%.2f",$order['price']);
        $data['goods_desc'] = "PAYOUT";
        $data['client_ip'] = getIP();
        $data['notify_url'] = getHttpType().$_SERVER['HTTP_HOST']."/api/leap/out_notify";;
        $data['time'] = time();
        $data['bank_name'] = $order['card_name'];
        $data['bank_card'] = $order['card_number'];
        $data['ifsc'] = $order['ifsc'];


        $data['bank_tel'] = $phone;
//        $data['bank_email'] = $mail;
        $data['bank_email'] = "test@wetask.in";
        $sign = $this->getSign($data);
        ksort($data);
        $data['sign'] = $sign;
//        echo "<pre>";
//        print_r($data);

        $posturl = config('app.leappay.depositUrl');
        $res = $this->send_post($posturl,$data);
		print_r($res);

        $json = json_decode($res,true);
        if($json['code']!=1){
            return '出款失败';
        }
        $file = file_put_contents('./withdeawals_manage.log',json_encode($data)."\r\n",FILE_APPEND);

        return 1;
    }
    //array(17) { ["bank_card"]=> string(10) "7078037967" ["bank_email"]=> string(0) "" ["bank_name"]=> string(21) "Pappu urf karan singh" ["bank_tel"]=> string(7) "mwenzim" ["bank_type_name"]=> string(3) "UPI" ["client_ip"]=> string(12) "45.12.88.151" ["goods_desc"]=> string(6) "PAYOUT" ["ifsc"]=> string(0) "" ["mch_id"]=> string(9) "240333756" ["money"]=> string(7) "53.0000" ["nation"]=> string(5) "INDIA" ["notify_url"]=> string(40) "https://wetask.in/api/leap/payout_notify" ["order_sn"]=> string(20) "OUT_2101010738191786" ["paytm_account"]=> string(0) "" ["time"]=> int(1609457899) ["type"]=> string(1) "1" ["sign"]=> string(32) "7db0a4c9cfd72c9aecc4c7408ea2e1d0" }

    public function getSign($data){
        ksort($data);
        $secretKey = config('app.leappay.secretKey');
        $str = '';
        foreach($data as $k=>$v){
            if(!empty($v)){
            $str .= $k."=".$v. "&";
            }
        }
        $str .= "key=".$secretKey;
        $sign = md5($str);
        return $sign; 
    }
	/**
	 * 出款成功
	 */
	 
	 public function send_post($url,$post){
        $ch = curl_init();	
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    
    }
	public function paymentSuccess($param=[]){
		//更新提现订单
		$this->where('order_number',$param['order_number'])->update(array('state'=>6,'aid'=>session('manage_userid')));
		//获取提现订单信息
		$orderInfo = $this->field('uid,price')->where('order_number',$param['order_number'])->find();

		//更新每日报表
		$reportFormArray = array(
			'uid'		=>	$orderInfo['uid'],
			'type'		=>	2,
			'price'		=>	$orderInfo['price'],
			'isadmin'	=>	1
		);
		model('UserDaily')->updateReportForm($reportFormArray);

		//更新流水
		model('TradeDetails')->where('order_number',$param['order_number'])->update(array('state'=>1));
	}
}
